<template>
  <el-table
    v-bind="$attrs"
    :data="formatData"
    :border="border"
    :center="center"
    fit
    class="tree-table"
  >
    <el-table-column
      v-for="(column, index) in columns"
      :key="index"
      :align="column.align ? column.align : 'left'"
      :label="column.label"
      :width="column.width ? column.width : ''"
      :min-width="column.minWidth ? column.minWidth : ''"
    >
      <template slot-scope="scope">
        <template v-if="index === columns.length - 1 && column.value === 'todo'">
          <slot :row="scope.row" />
        </template>
        <template v-else-if="column.value === 'index'">{{ scope.$index + 1 }}</template>
        <template v-else>
          <div v-html="itemValue(column, scope.row)" />
        </template>
      </template>
    </el-table-column>
  </el-table>
</template>

<script>
import treeToArray from './eval';

export default {
  name: 'TreeTable',
  props: {
    data: {
      type: [Array, Object],
      required: true
    },
    columns: {
      type: Array,
      default: () => []
    },
    evalFunc: {
      type: Function
    },
    evalArgs: {
      type: Array
    },
    border: {
      type: Boolean,
      default: false
    },
    center: {
      type: Boolean,
      default: false
    }
  },
  computed: {
    // 格式化数据源
    formatData: function () {
      let tmp;
      if (!Array.isArray(this.data)) {
        tmp = [this.data];
      } else {
        tmp = this.data;
      }
      const func = this.evalFunc || treeToArray;
      const args = this.evalArgs
        ? Array.concat([tmp, this.expandAll], this.evalArgs)
        : [tmp, this.expandAll];
      return func.apply(null, args);
    }
  },
  methods: {
    itemValue (item, scope) {
      return scope[item.value];
    }
  }
};
</script>

<style lang="scss" scoped></style>
